package dongze.com.ckdj.databinding;

import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.databinding.InverseBindingAdapter;
import android.databinding.InverseBindingListener;
import android.graphics.drawable.Drawable;
import android.support.annotation.IdRes;
import android.util.Pair;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import dongze.com.ckdj.adapter.InformationTextAdapter;
import dongze.com.ckdj.adapter.VehicleNumberAdapter;

/**
 * Created by fanqwz on 2017/7/24.
 */

public class BindingUtil {
    @BindingAdapter("binding")
    public static void setEntries(AutoCompleteTextView autoCompleteTextView, String[] entries) {
        if (entries != null && entries.length > 0) {
            autoCompleteTextView.setAdapter(new InformationTextAdapter(entries));

            if (autoCompleteTextView.getText() != null && entries.length == 1) {
                if (!entries[0].equals(autoCompleteTextView.getText().toString()))
                    autoCompleteTextView.showDropDown();
            } else {
                autoCompleteTextView.showDropDown();
            }
        } else {
            autoCompleteTextView.setAdapter(null);
            autoCompleteTextView.dismissDropDown();
        }
    }

    @BindingAdapter("binding")
    public static void setEntries(AutoCompleteTextView autoCompleteTextView, List<Pair<String, String>> entries) {
        if (entries != null && entries.size() > 0) {
            autoCompleteTextView.setAdapter(new VehicleNumberAdapter(entries));

            if (autoCompleteTextView.getText() != null && entries.size() == 1) {
                if (!(entries.get(0).first + "," + entries.get(0).second).equals(autoCompleteTextView.getText().toString()))
                    autoCompleteTextView.showDropDown();
            } else {
                autoCompleteTextView.showDropDown();
            }
        } else {
            autoCompleteTextView.setAdapter(null);
            autoCompleteTextView.dismissDropDown();
        }
    }

    @BindingAdapter(value = {"itemClicked"})
    public static void bindSelectionInverseBinding(AutoCompleteTextView autoCompleteTextView, final AdapterView.OnItemClickListener listener) {
        autoCompleteTextView.setOnItemClickListener(listener);
    }

    @BindingAdapter("selection")
    public static void setSelection(Spinner spinner, int selection) {
        spinner.setSelection(selection);
    }

    @BindingAdapter("date")
    public static void setDate(TextView textView, Date date) {
        textView.setText(new SimpleDateFormat("yyyy-MM-dd").format(date));
    }
    @BindingAdapter("time")
    public static void setTime(TextView textView, Date date) {
        textView.setText(new SimpleDateFormat("HH:mm").format(date));
    }


    @InverseBindingAdapter(attribute = "selection", event = "selectionChanged")
    public static int getSelection(Spinner spinner) {
        return spinner.getSelectedItemPosition();
    }

    @BindingAdapter("selectionChanged")
    public static void InverseBindingEvent(Spinner spinner, final InverseBindingListener inverseBindingListener) {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                inverseBindingListener.onChange();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                inverseBindingListener.onChange();
            }
        });
    }

    @BindingAdapter("positionText")
    public static void setPosition(RadioGroup radioGroup, String position) {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            if (((RadioButton) radioGroup.getChildAt(i)).getText() != null
                    && ((RadioButton) radioGroup.getChildAt(i)).getText().toString().equals(position)) {
                ((RadioButton) radioGroup.getChildAt(i)).setChecked(true);
                break;
            } else {
                ((RadioButton) radioGroup.getChildAt(i)).setChecked(false);
            }
        }
    }

    @InverseBindingAdapter(attribute = "positionText", event = "checkChanged")
    public static String getPosition(RadioGroup radioGroup) {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            if (((RadioButton) radioGroup.getChildAt(i)).isChecked()) {
                return ((RadioButton) radioGroup.getChildAt(i)).getText() == null ? null : ((RadioButton) radioGroup.getChildAt(i)).getText().toString();
            }
        }
        return null;
    }

    @BindingAdapter("data")
    public static void setAdapter(RadioGroup radioGroup, String[] data) {
        radioGroup.removeAllViews();
        for (String d :
                data) {
            RadioButton button = new RadioButton(radioGroup.getContext());
            button.setText(d);
            radioGroup.addView(button);
        }
    }

    @BindingAdapter("checkChanged")
    public static void setInverseBinding(RadioGroup group, final InverseBindingListener inverseBindingListener) {
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                inverseBindingListener.onChange();
            }
        });
    }

    @BindingAdapter("positionText")
    public static void setPosition(TableLayout tableLayout, List<String> position) {
        if (position == null)
            return;

        for (int i = 0; i < tableLayout.getChildCount(); i++) {
            TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
            for (int j = 0; j < tableRow.getChildCount(); j++) {
                if (((CheckBox) tableRow.getChildAt(j)).getText() != null
                        &&  (position.contains(((CheckBox) tableRow.getChildAt(j)).getText().toString()))) {
                    ((CheckBox) tableRow.getChildAt(j)).setChecked(true);
                } else {
                    ((CheckBox) tableRow.getChildAt(j)).setChecked(false);
                }
            }
        }
    }

    @InverseBindingAdapter(attribute = "positionText", event = "checkChanged")
    public static List<String> getPosition(TableLayout tableLayout) {
        List<String> values = new ArrayList<>();
        for (int i = 0; i < tableLayout.getChildCount(); i++) {
            TableRow tableRow = (TableRow) tableLayout.getChildAt(i);

            for (int j = 0; j < tableRow.getChildCount(); j++) {
                if (((CheckBox) tableRow.getChildAt(j)).isChecked()) {
                    values.add(((CheckBox) tableRow.getChildAt(j)).getText() == null ? null : ((CheckBox) tableRow.getChildAt(j)).getText().toString());
                }
            }
        }

        return values;
    }

    @BindingAdapter("checkChanged")
    public static void setInverseBinding(TableLayout tableLayout, final InverseBindingListener inverseBindingListener) {
        for (int i = 0; i < tableLayout.getChildCount(); i++) {
            TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
            for (int j = 0; j < tableRow.getChildCount(); j++) {
                ((CheckBox) tableRow.getChildAt(j)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        inverseBindingListener.onChange();
                    }
                });
            }
        }
    }


    @BindingAdapter(value = {"imageUrl", "placeHolder", "error"}, requireAll = false)
    public static void loadImage(ImageView imageView, String url, Drawable holderDrawable, Drawable errorDrawable) {
        Glide.with(imageView.getContext())
                .load(url)
                .placeholder(holderDrawable)
                .error(errorDrawable)
                .into(imageView);
    }

    @BindingConversion
    public static CharSequence convertDate(Date date) {
        if (date == null)
            return null;

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    @BindingConversion
    public static View.OnClickListener convertAction(Action action) {
        if (action == null)
            return null;

        return action.getOnClickListener();
    }

    @BindingConversion
    public static CharSequence convertActionName(Action action) {
        if (action == null)
            return null;

        return action.getName();
    }

    public static <T> boolean isNotEqual(T v1, T v2) {
        if ((v1 == null && v2 != null) || (v2 == null && v1 != null))
            return true;

        if (v1 != null)
            return !v1.equals(v2);

        return false;
    }
}
